<template>
  <div>
    <el-dialog class="public-dialog" :title="title" width="928" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
      <div>
        <template v-if="type != 'add'">
          <FormTitle title="变更单信息" />
          <div class="grid grid-cols-2 gap-y-3 mb-[16px]">
            <!-- <div class="after"></div> -->
            <VText v-for="item in changeOrderColumn" :key="item.key" :title="item.label" :value="formData?.[item.key]" line="1" />
          </div>
        </template>
        <FormTitle title="计划单信息" />
        <div>
          <el-button type="primary" class="mb-[8px]" v-if="!formData?.stocking_plan?.pr_number" @click="DialogStockUpRef.open()">选择</el-button>
        </div>
        <!--  -->
        <div class="form-box grid grid-cols-3 gap-y-3" v-if="formData?.stocking_plan?.pr_number">
          <VText v-for="item in orderColumn" :key="item.key" :title="item.label" :value="formData?.stocking_plan?.[item.key]" line="1" />
        </div>

        <FormTitle title="商品信息" />
        <template v-if="formData?.stocking_plan?.pr_number">
          <el-button type="primary" class="mb-[8px]" @click="DialogStockUpRef.open()">选择变更SKU</el-button>
        </template>

        <vxe-grid v-bind="tableOptions" ref="tableRef" />

        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="formData" :originOption="originOption">
          <template #IsNotify>
            <el-checkbox v-model="formData.is_notify" label="通知业务人员" :true-label="1" :false-label="0" />
          </template>
        </XForm>
        <div>
          <FormTitle title="变更原因" />
          <XForm ref="form" :fieldList="reasonFieldList" :options="formOption" :formData="formData" :originOption="originOption" class="grid grid-cols-3 mt-[16px]"> </XForm>
        </div>

        <div>
          <FormTitle title="审核信息" />
          <div v-for="(item, idx) in auditRow" :key="idx" class="mb-[8px] mt-[16px]">
            <p>{{ item.title }}</p>
            <div class="grid grid-cols-3 my-[8px]">
              <VText title="审核人员" style="width: 200px" :value="formData[item.user]" line="1" class="flex-1" />
              <VText title="审核时间" style="width: 200px" :value="formData[item.tiem]" line="1" />
            </div>
            <div>
              <VText title="审核备注" value=" " />
              <el-input v-model="formData[item.remark]" style="width: 320px" show-word-limit type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" />

              <!-- <VText :value="formData[item.remark]" line="1" class="w-[320px]" /> -->
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="handleClose"> 取消 </el-button>
        <el-button type="primary" :loading="loading" @click="submit"> 确认 </el-button>
      </template>
    </el-dialog>
    <DialogStockUp ref="DialogStockUpRef" @submit="handleSubmit" />
  </div>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import FormTitle from "@/components/XForm/FormTitle.vue"
import DialogStockUp from "./components/DialogStockUp.vue"
const DialogStockUpRef = ref()

import { spaChangeCreate, spaChangeUpdate } from "@/api/plan"
const handleSubmit = (row) => {
  console.log(1887766)
  console.log(row)
  formData.value = { ...row, ...formData.value, spa: { id: row.id } }
  // formData.value.spa = {
  //   id: row.id,
  // }
  console.log(tableOptions)
  tableOptions.data = [row]
}

import { spaChangeDetail } from "@/api/plan"
const modelValue = ref(false)
const data = reactive({
  title: "详情",
  type: "add",
  formData: {
    is_notify: 0,
  },
  // orderData: {
  //   stocking_plan: {},
  // },
  loading: false,
  value1: [],
})
const { title, type, formData, value1, loading } = toRefs(data)

// 变更单信息
const changeOrderColumn = ref([
  { label: "变更单号", key: "change_number" },
  { label: "状态", key: "review_status_text" },
  { label: "添加人员", key: "created_by_text" },
  { label: "添加时间", key: "created_at" },
])
// 计划单信息
const orderColumn = ref([
  { label: "变更单号", key: "pr_number" },
  { label: "计划状态", key: "plan_status" },
  { label: "计划类型", key: "plan_type_text" },
  { label: "计划部门", key: "planning_department" },
  { label: "添加人员", key: "created_by_text" },
  { label: "添加时间", key: "created_at" },
])

const auditRow = ref([
  { title: "计划审核", user: "plan_approver_by", tiem: "plan_review_time", remark: "plan_review_remark" },
  { title: "采购审核", user: "purchase_reviewer_by", tiem: "purchase_review_time", remark: "purchase_review_remark" },
  { title: "财务审核", user: "manager_reviewer_by", tiem: "manager_review_time", remark: "manager_review_remark" },
])

const tableRef = ref()
const reviewColor = {
  已驳回: "text-[#E50113] bg-[#FCE5E7]",
  已审核: "text-[#333] bg-[#F0F0F2]",
  // text-blue
}
// const orderTableData = ref([])
const tableOptions = reactive({
  border: true,
  rowConfig: { height: 160 },
  columns: [
    {
      title: "商品信息",
      width: 190,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <div class="flex mr-[4px]">
                <div class={`status-tag  mr-[2px] ${reviewColor[row.review_status_text] || "text-[#FAAD14] bg-[#FEF6E7]"}`}>{row.review_status_text}</div>
              </div>
              <div class="text-blue">SKU: {row.sku}</div>
            </div>
            <VText title="自定义" value={row.custom_sku} line={1} />
            <VText title="ASIN" value={row.asin} line={1} />
            <VText title="国家" value={row.site_code} line={1} />
          </div>
        ),
      },
    },
    { field: "sex", title: "变更前数量", width: 100 },
    {
      title: "人员信息",
      width: 100,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="计划" value={row.planner_user_text} line={1} />
            <VText title="采购" value={row.purchaser_user_text} line={1} />
            <VText title="运营" value={row.operator_user_text} line={1} />
          </div>
        ),
      },
    },
    {
      title: "采购单信息 x",
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="采购单" value={row.xxx} line={1} type="link" />
            <VText title="采购数量" value={row.xxx} line={1} />
            <VText title="状态" value={row.xxx} line={1} />
            <VText title="采购单" value={row.xxx} line={1} type="link" />
            <VText title="采购数量" value={row.xxx} line={1} />
            <VText title="状态" value={row.xxx} line={1} />
          </div>
        ),
      },
    },
    {
      title: "备货单信息 X",
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="备库单" value={row.xxx} line={1} type="link" />
            <VText title="发货数量" value={row.xxx} line={1} />
            <VText title="状态" value={row.xxx} line={1} />
            <VText title="备库单" value={row.xxx} line={1} type="link" />
            <VText title="发货数量" value={row.xxx} line={1} />
            <VText title="状态" value={row.xxx} line={1} />
          </div>
        ),
      },
    },
  ],
  data: [],
})

const originOption = ref({
  platform: [
    { label: "审核通过", value: "sku" },
    { label: "已驳回", value: "custom_sku" },
  ],
  "Plan.PlanSpaChange.ChangeTypeEnum": [{}, {}],
})
const formOption = ref({
  inline: true,
  // labelWidth: "100px",
  labelPosition: "top",

  rules: {
    change_type: [{ required: true, message: "请选择", trigger: "change" }],
    change_reason: [{ required: true, message: "请选择", trigger: "change" }],
  },
})
const fieldList = ref([
  {
    label: "变更类型",
    field: "change_type",
    type: "checkbox",
    options: {
      placeholder: "变更类型",
      data: [],
    },

    style: { width: "900px" },
  },
  { label: "变更后的数量", field: "after_stocking_quantity" },

  {
    label: "预计发货时间",
    field: "after_ship_time",
    type: "dateTimeRangeNorm",
    itemProps: {
      type: "datetime",
      shortcuts: [],
      valueFormat: "YYYY-MM-DD HH:mm:ss",
    },
  },
  {
    // 通知业务人员
    field: "is_notify",
    label: " ",
    slot: "IsNotify",
  },
  {
    field: "notify_user",
    label: " ",
    type: "cascader",
    multiple: true,
    collapseTags: true,
    placeholder: "业务人员",
  },
])
const reasonFieldList = ref([
  {
    label: "变更原因",
    field: "change_reason",
    type: "select",
    originField: "Plan.PlanSpaChange.ChangeReasonEnum",
    options: {
      placeholder: "变更原因",
    },
  },
])
// const rules = reactive({
//   sss: [{ required: true, message: "请选择", trigger: "change" }],
//   qqqqq: [{ required: true, message: "请选择", trigger: "change" }],
// })

// {"pr_number":"PR20240221627","change_type":[2],"after_stocking_quantity":"11","after_ship_time":"2024-03-26 00:00:00","is_notify":1,"notify_user":[385,394,465,350,351,351,466,467,482,482,352,80,81,208],"change_reason":1}
const submit = () => {
  let requests = null
  let keys = [...fieldList.value, ...reasonFieldList.value].map((v) => v.field)

  let params = {
    // "id": 12,
    // "pr_number": 1, //pr单号
    pr_number: formData.value?.stocking_plan?.pr_number,
    // "spa_id": 54, //计划明细id
    spa_id: formData.value?.spa?.id,
  }
  keys.forEach((key) => {
    params[key] = formData.value[key] || ""
  })
  if (type.value == "edit") {
    requests = spaChangeUpdate
    params.id = formData.value.id
  } else {
    requests = spaChangeCreate
  }

  console.log(params)
  requests(params).then((res) => {
    console.log(1232)
    console.log(res)
    ElMessage.success(res.message)

    formData.value = {}
    handleClose()
  })
}
const handleClose = () => {
  modelValue.value = false
}
const open = (params = {}) => {
  console.log(params)
  modelValue.value = true
  type.value = params.type || "add"
  if (params.type == "edit") {
    spaChangeDetail({ id: params.id }).then((res) => {
      console.log(11122)
      console.log(res)
      // res.data.change_type = JSON.parse(res.data.change_type)

      // res.data.plan_status = res.data.stocking_plan.plan_status
      // res.data.planning_department = res.data.stocking_plan.planning_department
      // res.data.plan_type_text = res.data.stocking_plan.plan_type_text
      // res.data.created_by_text = res.data.stocking_plan.created_by_text

      formData.value = res.data
      console.log(formData.value)
      tableOptions.data = [formData.value.spa]
    })
  } else {
    console.log(99999)
    console.log(params)
    if (params?.initForm) {
      console.log(params)
      formData.value = params.formData
      console.log(formData.value)
      tableOptions.data = [params.formData.row]
      return
    }

    if (params?.form?.id) {
      // console.log(111222)
      handleSubmit(params?.form)
    } else {
      // console.log(778899)
      tableOptions.data = []
    }
  }
  // setTimeout(() => {
  //   initEcharts()
  // }, 1000)

  // DialogStockUpRef.value.open()
}
const query = () => {
  // initEcharts()
}
// const form = ref()
// const formColumn = [
//   { label: "国家", key: "xxxxx" },
//   { label: "SKU", key: "xxxxx" },
//   { label: "ASIN", key: "xxxxx" },
//   { label: "自定义SKU", key: "xxxxx" },
//   { label: "总销量", key: "xxxxx" },
// ]

onMounted(() => {
  // let params = {
  //   type: "add",
  //   title: "新增",
  // }
  // DialogStockUpRef.value.open().

  getOption()
})
import { enumGet, enumOptions } from "@/api"
// import { getCountry, getSupplie } from "@/api"
const getOption = async () => {
  // let keys = [...fieldList.value, ...highFieldList.value].filter((v) => v.originField)

  // let enumParams = keys.filter((v) => v.enumOriginField).map((v) => v.originField)
  // const enumData = (await enumOptions({ params: enumParams }))?.data
  //
  // let enumGetName = keys.filter((v) => !v.enumOriginField).map((v) => v.originField)
  // enumGetName = [...enumGetName]
  const { data } = await enumGet({ name: ["Plan.PlanSpaChange.ChangeTypeEnum", "Plan.PlanSpaChange.ChangeReasonEnum"] })
  let optData = { ...data }
  for (const key in optData) {
    originOption.value[key] = optData[key]
  }

  // originOption.value.country = (await getCountry()).data
  // originOption.value.supplier = (await getSupplie())?.data
  console.log(1233)
  console.log(originOption.value)
  fieldList.value[0].options.data = originOption.value["Plan.PlanSpaChange.ChangeTypeEnum"]
}
defineExpose({
  open,
})
</script>
<style lang="scss" scoped>
.form-box {
  // border: 1px solid #eff3fe;
  // border-radius: 4px;
  // padding: 8px 12px;
  margin-bottom: 16px;
}
// .change-order {
//   background: #fef6e7;
//   padding: 10px 20px;
//   position: relative;
//   border-radius: 4px;
//   .after {
//     position: absolute;
//     left: 0;
//     top: 12px;
//     width: 5px;
//     height: 52px;
//     background: #faad14;
//     border-radius: 0px 100px 100px 0px;
//   }
// }
:deep(.status-tag) {
  height: 14px;
  line-height: 14px;
  padding: 0 3px;
  text-align: center;
  border-radius: 2px;
  font-size: 10px;
}
</style>
